ol.control.MeasureTools = function (options) {
    var element = $("<ul/>").addClass(options.className);

    if($(".control-full-screen").length>0) element.css("right", "250px");

    var liDist = $("<li/>").attr("type", "distance").append($("<span/>").attr("title", "测量距离")
            .addClass("iconfont icon-measure-distance")),
        liArea = $("<li/>").attr("type", "area").append($("<span/>").attr("title", "测量面积")
            .addClass("iconfont icon-measure-area"));

    element.append(liDist);
    if(options.isArea) element.append(liArea);

    var map = meteoMap;
    var draw = null;
    var listener;
    var sketch;
    var helpTooltipElement;
    var helpTooltip;
    var measureTooltipElement;
    var measureTooltip;
    var isMeasure = false,
        measureType = "";

    var source = new ol.source.Vector();
    var vector = new ol.layer.Vector({
        source: source,
        style: styleFunction
    });
    map.addLayer(vector);

    createHelpTooltip();

    map.on('pointermove', pointerMoveHandler);
    map.getViewport().addEventListener('mouseout', function() {
        helpTooltipElement.classList.add('hidden');
    });

    element.children().on("click", function () {
        clearMeasure();

        element.children().removeClass("active");
        $(this).addClass("active");

        isMeasure = true;
        measureType = $(this).attr("type");

        var type = (measureType === "area" ? 'Polygon' : 'LineString');
        draw = new ol.interaction.Draw({
            source: source,
            type: type,
            style: styleFunction,
            stopClick: true
        });
        map.addInteraction(draw);

        createMeasureTooltip(false);

        draw.on('drawstart', function(evt) {
            sketch = evt.feature;

            listener = sketch.getGeometry().on('change', function(evt) {
                var geom = evt.target;
                var output,
                    tooltipCoord = evt.coordinate;

                if (geom instanceof ol.geom.Polygon) {
                    output = formatArea(geom);
                    tooltipCoord = geom.getInteriorPoint().getCoordinates();
                }else{
                    output = formatLength(geom);
                    tooltipCoord = geom.getLastCoordinate();
                }

                measureTooltipElement.innerHTML = output;
                measureTooltip.setPosition(tooltipCoord);
            });
        });
        draw.on('drawend', function(evt) {
            isMeasure = false;
            sketch = null;
            ol.Observable.unByKey(listener);
            map.removeInteraction(draw);
            helpTooltip.setPosition(null);

            measureTooltipElement.className = 'tooltip tooltip-static measure-result';
            var close = $("<span/>").addClass("close").attr("title", "关闭").html("×");
            close.on("click", function () {
                clearMeasure();
            });
            $(measureTooltipElement).append(close);
            measureTooltip.setOffset([0, -7]);
            measureTooltipElement = null;

            createMeasureTooltip();
        });
    });

    function clearMeasure() {
        element.children().removeClass("active");
        source.clear();
        $($(".measure-result").parent()).remove();
        if(draw) map.removeInteraction(draw);
    }
    
    function styleFunction(feature) {
        var styles = [new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.2)'
            }),
            stroke: new ol.style.Stroke({
                color: 'rgba(255, 0, 0, 0.5)',
                width: 4
            })
        })];
        if(measureType==="distance") {
            var geometry = feature.getGeometry();
            var coords = geometry.getCoordinates();
            coords = coords.length > 1 ? coords : coords[0];
            for (var i = 0; i < coords.length; i++) {
                var coord = coords[i];
                styles.push(new ol.style.Style({
                    geometry: new ol.geom.Point(coord),
                    image: new ol.style.Circle({
                        radius: 3,
                        fill: new ol.style.Fill({
                            color: '#ffffff'
                        }),
                        stroke: new ol.style.Stroke({
                            color: '#ff0000',
                            width: 1
                        })
                    })
                }));
            }
        }
        return styles;
    }
    
    function pointerMoveHandler(evt) {
        if (evt.dragging) {
            return;
        }
        var helpMsg = '点击开始测量';
        if (sketch) {
            helpMsg = "点击继续测量，双击结束测量";
        }
        helpTooltipElement.innerHTML = helpMsg;
        if(isMeasure) {
            helpTooltip.setPosition(evt.coordinate);
        }
        helpTooltipElement.classList.remove('hidden');
    }
    
    function formatLength(line) {
        var length = ol.Sphere.getLength(line);
        var output;
        if (length > 1000) {
            output = (Math.round(length / 1000 * 100) / 100) +
                ' ' + '千米';
        } else {
            output = (Math.round(length * 100) / 100) +
                ' ' + '米';
        }
        return output;
    }

    function formatArea(polygon) {
        var area = ol.Sphere.getArea(polygon);
        var output;
        if (area > 10000) {
            output = (Math.round(area / 1000000 * 100) / 100) +
                '平方千米';
        } else {
            output = (Math.round(area * 100) / 100) +
                ' ' + '平方米';
        }
        return output;
    }

    function createHelpTooltip() {
        if (helpTooltipElement) {
            helpTooltipElement.parentNode.removeChild(helpTooltipElement);
        }
        helpTooltipElement = document.createElement('div');
        helpTooltipElement.className = 'tooltip hidden';
        helpTooltip = new ol.Overlay({
            element: helpTooltipElement,
            offset: [15, 0],
            positioning: 'center-left'
        });
        map.addOverlay(helpTooltip);
    }

    function createMeasureTooltip() {
        if (measureTooltipElement) {
            measureTooltipElement.parentNode.removeChild(measureTooltipElement);
        }
        measureTooltipElement = document.createElement('div');
        measureTooltipElement.className = 'tooltip tooltip-measure';
        measureTooltip = new ol.Overlay({
            element: measureTooltipElement,
            offset: [0, -15],
            positioning: 'bottom-center'
        });
        map.addOverlay(measureTooltip);
    }

    ol.control.Control.call(this, {
        element: element[0],
        target: null
    });
};
ol.inherits(ol.control.MeasureTools, ol.control.Control);